<?php

/**
 * Name: 值班领导记录仓储层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:30:00
 */

namespace App\Repositories\Checkin;

use App\Models\Checkin\DutySupervisor;
use App\Repositories\BaseRepository;

class DutySupervisorRepository extends BaseRepository
{
    public function __construct(DutySupervisor $model)
    {
        parent::__construct($model);
    }

    /**
     * 创建或更新记录
     */
    public function updateOrCreate(array $attributes, array $values = [])
    {
        return $this->model->updateOrCreate($attributes, $values);
    }

    /**
     * 获取指定日期的值班领导
     */
    public function getDutySupervisorByDate($date)
    {
        return $this->query()
            ->where('duty_date', $date)
            ->with('supervisor')
            ->first();
    }

    /**
     * 设置值班领导
     */
    public function setDutySupervisor($supervisorData, $dutyInfo = [], $date = null)
    {
        $date = $date ?: today();

        // 只提取需要的字段，避免将date字段混入
        $data = [
            'duty_date' => $date,
            'supervisor_id' => $supervisorData['id'],
            'supervisor_name' => $supervisorData['name'],
            'phone' => $dutyInfo['phone'] ?? $supervisorData['phone'] ?? '',
            'remark' => $dutyInfo['remark'] ?? '',
            'is_notified' => false,
            'notified_at' => null,
        ];

        return $this->updateOrCreate([
            'duty_date' => $date,
        ], $data);
    }

    /**
     * 获取当天的值班领导
     */
    public function getTodayDutySupervisor()
    {
        return $this->getDutySupervisorByDate(today());
    }

    /**
     * 获取未通知的值班领导
     */
    public function getUnnotifiedDutySupervisors($date = null)
    {
        $date = $date ?: today();

        return $this->query()
            ->where('duty_date', $date)
            ->where('is_notified', false)
            ->with('supervisor')
            ->get();
    }

    /**
     * 标记为已通知
     */
    public function markAsNotified($id)
    {
        return $this->update($id, [
            'is_notified' => true,
            'notified_at' => now()
        ]);
    }

    /**
     * 获取值班领导列表（分页）
     */
    public function getDutySupervisorsList($perPage = 15, $filters = [])
    {
        $query = $this->query();

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('duty_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('duty_date', '<=', $filters['end_date']);
        }

        // 领导筛选
        if (isset($filters['supervisor_id'])) {
            $query->where('supervisor_id', $filters['supervisor_id']);
        }

        return $query->with('supervisor')
                    ->orderBy('duty_date', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 获取某个领导的值班记录
     */
    public function getSupervisorDutyRecords($supervisorId, $perPage = 15, $filters = [])
    {
        $query = $this->query()->where('supervisor_id', $supervisorId);

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('duty_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('duty_date', '<=', $filters['end_date']);
        }

        return $query->orderBy('duty_date', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 检查指定日期是否已设置值班领导
     */
    public function hasDutySupervisor($date)
    {
        return $this->query()
            ->where('duty_date', $date)
            ->exists();
    }

    /**
     * 获取最近的值班领导记录
     */
    public function getRecentDutySupervisors($limit = 10)
    {
        return $this->query()
            ->with('supervisor')
            ->orderBy('duty_date', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * 获取值班领导统计信息
     */
    public function getDutyStatistics($startDate, $endDate)
    {
        return $this->query()
            ->whereBetween('duty_date', [$startDate, $endDate])
            ->selectRaw('supervisor_id, supervisor_name, COUNT(*) as duty_count')
            ->groupBy('supervisor_id', 'supervisor_name')
            ->orderByDesc('duty_count')
            ->get();
    }

    /**
     * 根据值班人员id获取详情信息
     */
    public function getSupervisorDetailById($supervisorId)
    {
        // 获取值班人员的所有值班记录
        $dutyRecords = $this->query()
            ->where('supervisor_id', $supervisorId)
            ->orderBy('duty_date', 'desc')
            ->get();

        // 获取值班人员基本信息（通过关联的 supervisor）
        $supervisorInfo = null;
        if ($dutyRecords->isNotEmpty()) {
            $firstRecord = $dutyRecords->first();
            $supervisorInfo = [
                'id' => $supervisorId,
                'name' => $firstRecord->supervisor_name,
                'phone' => $firstRecord->phone,
            ];

            // 如果有关联的 supervisor 模型，获取更完整的信息
            if ($firstRecord->supervisor) {
                $supervisorInfo = array_merge($supervisorInfo, [
                    'team' => $firstRecord->supervisor->team ?? '',
                    'position' => $firstRecord->supervisor->position ?? '',
                    'user_id' => $firstRecord->supervisor->user_id ?? null,
                ]);
            }
        }

        return [
            'supervisor_info' => $supervisorInfo,
            'duty_records' => $dutyRecords,
            'total_duty_count' => $dutyRecords->count(),
        ];
    }
}

